	  // Enter a client ID for a web application from the Google Developer Console.
      // The provided clientId will only work if the sample is run directly from
      // https://google-api-javascript-client.googlecode.com/hg/samples/authSample.html
      // In your Developer Console project, add a JavaScript origin that corresponds to the domain
      // where you will be running the script.
      var clientId = '549757693316-l2f3vcg8p8d4sjto74ksq9603u9omkfj.apps.googleusercontent.com';

      // Enter the API key from the Google Develoepr Console - to handle any unauthenticated
      // requests in the code.
      // The provided key works for this sample only when run from
      // https://google-api-javascript-client.googlecode.com/hg/samples/authSample.html
      // To use in your own application, replace this API key with your own.
      var apiKey = 'AIzaSyCWLPAcvKGNncL5FXbHwOGqMYaBKW497Jo';
	  var currentEvent;
	  var numberOfSectionsInAccordion=0;

      // To enter one or more authentication scopes, refer to the documentation for the API.
      var scopes = "https://www.google.com/m8/feeds https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/userinfo.email";
	  
	  $(document).ready(function(){
		  //var testString = "<p> this is a test string</p>"
		  //var content_div = document.getElementById("content_div");
		  //content_div.innerHTML = testString;
		  //var timeZoneOffSet;
		  //var head = document.getElementsByTagName("head");
		  //var output = "<link rel='stylesheet' herf='https://dl.dropboxusercontent.com/u/4759136/iMeetAppGadget/trunk/iMeetAppGadgetStyleSheet.css' type='text/css' media='all'/>";
		  //head.innerHTML = output;
		  
	  });
function addAutocomplete(){
	console.log("addAutocomplete Called");
  $(function() {
      
      var tag = $( "#numberTextBox" ).autocomplete({
		minLength: 2,
		delay: 300,  
        source: function( request, responseFn ) {
        var term = request.term;
        console.log("this is the search text:" + term);
		getContacts(term,function(entry){
			var NamesArray =[];
			for (var i = 0; i < entry.length; i++) {
				if (entry[i].gd$name){
			    NamesArray.push(entry[i].gd$name.gd$fullName.$t);
			}
			}
			//console.log("this is entry:" + entry);
			responseFn(entry);
		});
		},
		position: { my : "right top", at: "left bottom", collision: "fit flip"},
		select: function( event, ui ) {
			
		        //$( "#content_div" ).html( ui.item.gd$name.gd$fullName.$t );
				createSelectableItems(ui.item);
				 $( "#numberTextBox" ).val( "" );
				gadgets.window.adjustHeight();
				  
		        // $( "#project-id" ).val( ui.item.value );
// 		        $( "#project-description" ).html( ui.item.desc );
// 		        $( "#project-icon" ).attr( "src", "images/" + ui.item.icon );
 
		        return false;
		      },
			  focus: function( event, ui ) {
				  var name = getItemName(ui.item);
			          $( "#numberTextBox" ).val( name );
			          return false;
			        }
			  
	}
);
	tag.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
		var label= getItemName(item);
		var contactProperties="";
		
		if(item.gd$email){
			var emailsString = "";
			for (var i = 0; i < item.gd$email.length; i++){
				emailsString += item.gd$email[i].address+ "</br>";
			}
			contactProperties += emailsString;
		}
		if(item.gd$phoneNumber){
			var phonesString = "";
			for (var i = 0; i < item.gd$phoneNumber.length; i++){
				phonesString += item.gd$phoneNumber[i].$t+ "</br>";
			}
			contactProperties += phonesString;
		}
		var autoCompleteLineText = $( "<li>" )
		        .append( "<a> <font size='2'>" + label + "</font>" + "<font size='1'></br>" + contactProperties+ "</font></a>" )
		        .appendTo( ul );
				return autoCompleteLineText;
		    };
			
tag.data( "ui-autocomplete" )._resizeMenu= function() {
  this.menu.element.outerWidth( 162 );
};
}	
   );
}	
function getItemPhoneNumbersArray(item){
	var phoneNumbers  = new Array();
	if(item.gd$phoneNumber)
	{
		for (var i = 0; i < item.gd$phoneNumber.length; i++){
			phoneNumbers[i]=item.gd$phoneNumber[i].$t;
		}
		
	}
	return phoneNumbers;
}
function getItemEmailsArray(item){
	var emails = new Array();
	if(item.gd$email)
	{
		for (var i = 0; i < item.gd$email.length; i++){
			emails[i]=item.gd$email[i].address;
		}
		
	}
	return emails;
}

function getItemName(item){
	var label;
	if(item.gd$name){
		label= item.gd$name.gd$fullName.$t;
	}
	else {label = "No Name";}
	return label;
}

	  function addAuthButton(){
		var content =document.getElementById('content_div');
		createButton(content,handleAuthClick,"Please Authorize Me","authorizeMeButton");
	  }
	  addAuthButton();
	function addTextBox(){
	console.log("addTextBox called");
	 var main = document.getElementById('results');
	 main.innerHTML = "";
	   
	  var input = document.createElement('input'),
	  div = document.createElement('div');
	  div2 = document.createElement('div');
	  div2.id="menu-container";
	  input.type = "text";
	  input.id = "numberTextBox";
	  input.placeholder="Search for contact"; 
	  
	   div.appendChild(input);
	  main.appendChild(div);
	  addAutocomplete();
	  //createButton(main,addButtonFunc, "Add Reminder","addReminder");
	  
	  }  
	function createButton(context, func,text,id){
    var button = document.createElement("input");
    button.type = "button";
    button.value = text;
    button.onclick = func;
	button.id= id;
    context.appendChild(button);
}
function addButtonFunc(){
	console.log("add button func called");
	var input = document.getElementById('numberTextBox');
	var number= input.value;
	console.log(number);
	addNumberToEvent(number);
	updateEvent(currentEvent,number);

}
function addNumberToEvent(number){
	
}
	function myFunction()
	{
	 
	 //makeRequest();
	//fetchData();
	 //getContacts();
	 //getHtml();
	//load();
	//var output= document.getElementById('paragraph');
	} 
	function appendResults(text) {
        var results = document.getElementById('results');
        results.appendChild(document.createElement('P'));
        results.appendChild(document.createTextNode(text));
      }

   function insertEvent() {
   
    console.log("makeReq called");
	var eventR = {
	"start": {
		"dateTime": "2014-01-12T13:00:00Z"
				},
		"end": {
		"dateTime": "2014-01-12T14:00:00Z"
		}
	};
        var request = gapi.client.calendar.events.insert({
          'calendarId': 'primary',
			'resource': eventR
		
        });
        request.execute(function(response) {
           console.log(response);
        });
      }
	  
	  function getContacts(query,callback){
	var maxResults = 4;	  
	  console.log("getContact called");
	 
	 var authParams = gapi.auth.getToken();	
var req = gapi.client.request({
'path': '/m8/feeds/contacts/default/full',
'headers':{'GData-Version':'3.1'},
'method': 'GET',
'params':{ 'alt':'json','access_token':authParams.access_token, 'q':query ,'max-results':maxResults}
 });
 console.log(req);
 
 req.execute(function(response) { 
	 console.log("this is entry: ");
	 console.log(response.feed.entry);	 
	 callback(response.feed.entry);
  });
	
	  
	  }

      function load() {
		console.log("load called");
        gapi.client.setApiKey(apiKey);
		checkAuth();
        gapi.client.load('calendar', 'v3',function(data){});
		
		//
      } 
	  
function checkAuth() {
	console.log("checkAuth Called");
	          gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
	        };
		

function handleAuthResult(authResult) {
				console.log("handleAuthResult called");
	          var authorizeButton = document.getElementById('authorizeMeButton');
	          if (authResult && !authResult.error) {
	            authorizeButton.style.visibility = 'hidden';
	          } else {
	            authorizeButton.style.visibility = '';
	            authorizeButton.onclick = handleAuthClick;
	          }
	        }

	  
	  function handleAuthClick() {
	  console.log("Auth called");
	  	
	          var config = {
	        'client_id': clientId,
	  	  //'apiKey':apiKey,
	  	  'scope': scopes,
		  'immediate': false
	          };
	          gapi.auth.authorize(config, function() {
	            console.log('login complete');
	            console.log(gapi.auth.getToken());
	          });
	        }
			
function createSelectableItems(item){
	
	//var content_div = document.getElementById("content_div");
	
	//var object = document.getElementById('accordion');
	var newDiv = document.createElement('div');
	
	var name = getItemName(item);
	
	var headLine = document.createElement('h3');
	headLine.innerHTML = name;
	newDiv.appendChild(headLine);
	var ol = document.createElement('ol');
	ol.id = 'selectable';
	var emails = new Array();
	emails = getItemEmailsArray(item);
	for (var i = 0; i < emails.length; i++){
		var li = document.createElement('li');  
		li.class = 'ui-widget-content';
		li.innerHTML = "<h4>" +emails[i] +"</h4>";
		ol.appendChild(li);
	}
	var phoneNumbers = new Array();
	phoneNumbers=getItemPhoneNumbersArray(item);
	for (var i = 0; i < phoneNumbers.length; i++){
		var li = document.createElement('li');  
		//var phoneTextLabel= document.createElement('H4');
		li.class = 'ui-widget-content';
		li.innerHTML = phoneNumbers[i];
		//li.appendChild(phoneTextLabel);
		ol.appendChild(li);
	}
	
	//newDiv.appendChild(ol);
	//object.appendChild(headLine);
	//$(function() {
		
		$( "#accordion").append(newDiv);
		$( "#accordion").append(ol);
	    $( "#accordion" ).accordion("refresh");
		$( "#accordion" ).accordion( "option", "active", numberOfSectionsInAccordion);
		$( "#selectable" ).selectable();
		numberOfSectionsInAccordion ++;
	 // });
//	$(function(){
	    
	 // });
	  
	//content_div.appendChild(object);
	
}	  
function subscribeEventCallback(calendarEvent) {

  var out;
  if (!calendarEvent) { 
	 var main = document.getElementById('results');
	 main.innerHTML = "";
     out = 'Click on event to get Started';
     var element = document.getElementById('content_div');
     element.innerHTML = out;
	 currentEvent='';
 
  } else {
  console.log(calendarEvent);
  currentEvent= calendarEvent;
  addTextBox();
var content_div = document.getElementById("content_div");
content_div.innerHTML='';
var object = document.createElement('div');
numberOfSectionsInAccordion=0;
object.id ="accordion";
content_div.appendChild(object);
//$( "#accordion" ).accordion();
$( "#accordion" ).accordion({
      heightStyle: "content",
	  collapsible: true
    });



listEvent(calendarEvent,function(eventObject){
   getEvent(eventObject);
});
  }
  
   //var element = document.getElementById('content_div');
   //element.innerHTML = out;
  
   
   //updateEvent(calendarEvent);
 
  // getDayTime(calendarEvent.startTime);
 
   //makeRequest();
}
$(function() {
    $( "#accordion-resizer" ).resizable({
      minHeight: 140,
      minWidth: 200,
      resize: function() {
        $( "#accordion" ).accordion( "refresh" );
      }
    });
  });
function displayEvent(eventObject){
	var out = '';
	if (eventObject.summary) {
	      out += 'Title = ' + eventObject.summary + '<br>';
	      }
		  if('attendees' in eventObject){
		  		
		  		out += 'Attendees: ' + '/n';
		  		var attends= eventObject['attendees'];
		  		
		  		for (var i=0;i<attends.length;i++)
		  		{ 
		  		out += (attends[i].email + "/n");
				//getContacts(attends[i].email);
		  		//console.log(attends[i]);
		  		
		  		}
		  	//out += 'Attendees: ' + calendarEvent['attendees'] + '\n';
		  	}
		  
	      var element = document.getElementById('content_div');
	      element.innerHTML = out;
}
	  
google.calendar.read.subscribeToEvents(subscribeEventCallback);


function preferencesCallback(prefs) {
     //console.log("time zone offset:" + prefs.timezone_offset);
	 timeZoneOffSet = toTimeZoneFormat(prefs.timezone_offset/1000);
	 
 console.log("time zone offset:" + timeZoneOffSet);
}
google.calendar.getPreferences(preferencesCallback);


function getHtml() {  
console.log("getHtml called");  
  var params = {};  
  params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;  
  params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.OAUTH;
   params[gadgets.io.RequestParameters.OAUTH_SERVICE_NAME] = "google";
   params[gadgets.io.RequestParameters.OAUTH_TOKEN_NAME]="contacts";
   //params[gadgets.io.RequestParameters.OAUTH_REQUEST_TOKEN] = "ya29.1.AADtN_Wv3Ct8uZp3gKIKlYVC4i8CnQAcX5Pgko5CouWQou2WpHBUKzg3YtRAep-SDmqNHfQ";
   params[gadgets.io.RequestParameters.OAUTH_USE_TOKEN] = "always";
   params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
  var url = "http://www.google.com/m8/feeds/contacts/default/full/";  
  gadgets.io.makeRequest(url, response, params);
};
function response(obj) {  
console.log("response called");
  //obj.text contains the text of the page that was requested  
  console.log(obj.text);
  var str = obj.text;
  var html =  str.substr(0,400);  
  //document.getElementById('paragraph').innerHTML = html;
};
 function fetchData() {
      var params = {};
      url = "http://www.google.com/m8/feeds/contacts/default/full?alt=json";
      params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
      params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.OAUTH;
      params[gadgets.io.RequestParameters.OAUTH_SERVICE_NAME] = "google";
	  params[gadgets.io.RequestParameters.OAUTH_TOKEN_NAME]="contacts";
      params[gadgets.io.RequestParameters.OAUTH_USE_TOKEN] = "always";
	  //params[gadgets.io.RequestParameters.OAUTH_REQUEST_TOKEN] ="ya29.1.AADtN_XkIl5Q1zFEmAjC6feIHAmAnzAJ01woK0-rRXOpfRoD1BhMGiWOWOG6wbs";
	 //params[gadgets.io.RequestParameters.OAUTH_REQUEST_TOKEN_SECRET]="u7XhAlCulY1DCxRkBO7BblK_";
      params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;

      gadgets.io.makeRequest(url, function (response) {
	 console.log(response);
        if (response.oauthApprovalUrl) {
          // Create the popup handler. The onOpen function is called when the user
          // opens the popup window. The onClose function is called when the popup
          // window is closed.
		  // Gadgets.oauth.Popup
          var popup = shindig.oauth.popup({
            destination: response.oauthApprovalUrl,
            windowOptions: null,
            onOpen: function() { showOneSection('waiting'); },
            onClose: function() { fetchData(); }
          });
          // Use the popup handler to attach onclick handlers to UI elements.  The
          // createOpenerOnClick() function returns an onclick handler to open the
          // popup window.  The createApprovedOnClick function returns an onclick
          // handler that will close the popup window and attempt to fetch the user's
          // data again.
          var personalize = document.getElementById('personalize');
          personalize.onclick = popup.createOpenerOnClick();
          var approvaldone = document.getElementById('approvaldone');
          approvaldone.onclick = popup.createApprovedOnClick();
          showOneSection('approval');
        } else if (response.data) {
            showOneSection('main');
            showResults(response.data);
        } else {
            // The response.oauthError and response.oauthErrorText values may help debug
            // problems with your gadget.
            var main = document.getElementById('main');
            var err = document.createTextNode('OAuth error: ' +
              response.oauthError + ': ' + response.oauthErrorText);
            main.appendChild(err);
            showOneSection('main');
        }
      } , params);
	  
    }
	function showOneSection(toshow) {
      var sections = [ 'main', 'approval', 'waiting' ];
      for (var i=0; i < sections.length; ++i) {
        var s = sections[i];
        var el = document.getElementById(s);
        if (s === toshow) {
          el.style.display = "block";
        } else {
          el.style.display = "none";
        }
      }
    }
	function showResults(result) {
		
      showOneSection('main');

      var titleElement = document.createElement('div');
      var nameNode = document.createTextNode(result.feed.title.$t);
      titleElement.appendChild(nameNode);
      document.getElementById("content_div").appendChild(titleElement);
      document.getElementById("content_div").appendChild(document.createElement("br"));

      list = result.feed.entry;
	  console.log(list);

      for(var i = 0; i < list.length; i++) {
        entry = list[i];
        var divElement = document.createElement('div');
        divElement.setAttribute('class', 'name');
        divElement.appendChild(nameNode);
        if (entry.gd$phoneNumber) {
          var valueNode = document.createTextNode(entry.gd$phoneNumber[0].$t);
          divElement.appendChild(valueNode);
        }
        document.getElementById("content_div").appendChild(divElement);
      }
    }
	function getEvent(eventObject){
		console.log("getEvent called");
		var request = gapi.client.calendar.events.get({
		'eventId': eventObject.id, 'calendarId': 'primary'
		});
		console.log(request);
        request.execute(function(response) {
           console.log(response);
		   //displayEvent(response);
		   
        });
	}
	
	function updateEvent(calendarEvent,phoneNumber){
	console.log("updateEvent called");
	var iMeetAppEmailNumber = phoneNumber + "@cal2sms.com";
       
			
       
		listEvent(calendarEvent, function(eventObject){
		var attendees= eventObject.attendees;
		attendees.push(
			{
      "email":iMeetAppEmailNumber
    }
);
		var eventR = {"attendees": attendees};	
		var request = gapi.client.calendar.events.patch({
		'eventId': eventObject.id, 'calendarId': 'primary',sendNotifications:true,'resource': eventR
		});
		console.log(request);
        request.execute(function(response) {
           console.log(response);
		   refreshCalendar();
		   
        });
		});
		}
	function listEvent(event, callback){
		console.log("listEvent called");
		
		var timeMin= getDayTime(event.startTime);
		var timeMax = getDayTime(event.endTime);
		var request = gapi.client.calendar.events.list({
		 'calendarId': 'primary',
		 'timeMin': timeMin,
		 'timeMax': timeMax
		});
		console.log(request);
        request.execute(function(response) {
           console.log(response);
		   if (response.items){
		   console.log("there is items");
		  
		   console.log("event id is: " + response.items[0].id);
		    
		  callback(response.items[0]);

		   }
		   
        });
	}
	function getDayTime(dateTime){
	var dateTimeString= dateTime.year + "-" + dateTime.month + "-" + dateTime.date + "T" + dateTime.hour + ":" + dateTime.minute + ":" + dateTime.second+"+" +timeZoneOffSet;// + "Z"
	console.log("getDateTime called");
	console.log(dateTimeString);
	return dateTimeString;
	}
	
	function toTimeZoneFormat(timeInSec){
   
    var hours   = Math.floor(timeInSec / 3600);
    var minutes = Math.floor((timeInSec - (hours * 3600)) / 60);


    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    //if (seconds < 10) {seconds = "0"+seconds;}
    var time    = hours+':'+minutes//+':'+seconds;
    return time;
}
function refreshCalendar(){
	console.log("refresh calendar called" );
	google.calendar.refreshEvents();
	subscribeEventCallback(currentEvent);	
}
function dataChangeCallback() {
  console.log('New data is likely available');
}
google.calendar.subscribeToDataChange(dataChangeCallback);
	//gadgets.util.registerOnLoadHandler(fetchData);
//gadgets.util.registerOnLoadHandler(getHtml);
